package tld.lxcloud.chatdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import tld.lxcloud.chatdemo.model.ChatMessage;
import tld.lxcloud.chatdemo.model.NotifyMessage;

@Controller
public class ChatController {

    @Autowired
    private SimpMessageSendingOperations messagingTemplate;

    @MessageMapping("/chat.sendMessage")
    @SendTo("/topic/public")
    public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
        return chatMessage;
    }

    @MessageMapping("/chat.addUser")
    @SendTo("/topic/public")
    public ChatMessage addUser(@Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) {
        // Add username in web socket session
        headerAccessor.getSessionAttributes().put("username", chatMessage.getSender());
        return chatMessage;
    }

    @PostMapping("/notify")
    @ResponseBody
    public ChatMessage sendMessage(@RequestBody NotifyMessage message) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSender("notifier");
        chatMessage.setType(ChatMessage.MessageType.NOTIFY);
        chatMessage.setContent(message.getContent());
        if (StringUtils.isEmpty(message.getReceiver())) {
            // public message
            messagingTemplate.convertAndSend("/topic/public", chatMessage);
        } else {
            // private message
            chatMessage.setContent(message.getReceiver() + "," + message.getContent());
            messagingTemplate.convertAndSend("/topic/private/" + message.getReceiver(), chatMessage);
        }
        return chatMessage;
    }
}